import Sprite2DApplication from "../../src/spriteSystem/Sprite2DApplication";
import ISprite from "../../src/interfaces/ISprite";
import SpriteFactory from "../../src/factorys/SpriteFactory";
import EInputEventType from "../../src/enums/EInputEventType";
import CanvasKeyBoardEvent from "../../src/events/CanvasKeyBoardEvent";
import Vector2 from "../../src/maths/Vector2";
import TankShape from "./TankShape";

export default class SimpleTankTest {
    private _app: Sprite2DApplication;
    private _tankSprite: ISprite;
    private _turretSprite: ISprite;

    private _tank: ISprite;

    public constructor(app: Sprite2DApplication) {
        this._app = app;

        this._tankSprite = SpriteFactory.createSprite(SpriteFactory.createRect(80, 50, 0.5, 0.5));
        this._tankSprite.fillStyle = 'blue';
        this._tankSprite.x = 200;
        this._tankSprite.y = 300;
        this._tankSprite.keyEvent = this.keyEvent.bind(this);

        this._turretSprite = SpriteFactory.createSprite(SpriteFactory.createXLine(100));
        this._turretSprite.strokeStyle = 'red';
        this._turretSprite.lineWidth = 5;
        this._turretSprite.x = 200;
        this._turretSprite.y = 300;
        this._turretSprite.keyEvent = this.keyEvent.bind(this);

        this._tank = SpriteFactory.createSprite(new TankShape());
        this._tank.x = 400;
        this._tank.y = 300;
        this._tank.fillStyle = 'green';
        this._tank.keyEvent = this.keyEvent.bind(this);

        this._app.rootContainer.addSprite(this._tankSprite);
        this._app.rootContainer.addSprite(this._turretSprite);
        this._app.rootContainer.addSprite(this._tank);

        this._app.start();
    }

    private keyEvent(spr: ISprite, evt: CanvasKeyBoardEvent): void {
        if (evt.type === EInputEventType.KEYPRESS) {
            if (evt.key === 'a') {
                this._tankSprite.rotation += 2;
                this._turretSprite.rotation += 2;
            } else if (evt.key === 'q') {
                this._tankSprite.rotation -= 2;
                this._turretSprite.rotation -= 2;
            } else if (evt.key === 'd') {
                this._turretSprite.rotation += 5;
            } else if (evt.key === 'e') {
                this._turretSprite.rotation -= 5;
            } else if (evt.key === 'w') {
                let forward: Vector2 = this._tankSprite.getWorldMatrix().xAxis;
                this._tankSprite.x += forward.x * 3;
                this._tankSprite.y += forward.y * 3;
                this._turretSprite.x += forward.x * 3;
                this._turretSprite.y += forward.y * 3;
            } else if (evt.key === 's') {
                let forward: Vector2 = this._tankSprite.getWorldMatrix().xAxis;
                this._tankSprite.x -= forward.x * 3;
                this._tankSprite.y -= forward.y * 3;
                this._turretSprite.x -= forward.x * 3;
                this._turretSprite.y -= forward.y * 3;
            }
        }
    }
}